package com.fay.mymiaosha.service.impl;

import com.fay.mymiaosha.dao.PromoDoMapper;
import com.fay.mymiaosha.dataobject.PromoDo;
import com.fay.mymiaosha.service.IPromoService;
import com.fay.mymiaosha.service.model.PromoModel;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Objects;

/**
 * @Title:
 * @Description:
 * @Author Fay Wang
 * @Date 2022/3/19 17:19
 * @Version 1.0
 */
@Service
public class PromoServiceImpl implements IPromoService {

    @Autowired
    private PromoDoMapper promoDoMapper;

    @Override
    public PromoModel getPromoByItemId(Integer itemId) {
        PromoDo promoDo = promoDoMapper.selectByItemId(itemId);

        PromoModel promoModel = convertFromPromoDo(promoDo);

        if (promoModel == null) {
            return null;
        }
        // judge time
        if (promoModel.getStartTime().isAfterNow()) {
            // not start
            promoModel.setStatus(1);
        } else if (promoModel.getEndTime().isBeforeNow()) {
            promoModel.setStatus(3);
        } else {
            promoModel.setStatus(2);
        }
        return promoModel;
    }

    private PromoModel convertFromPromoDo(PromoDo promoDo) {
        if (Objects.isNull(promoDo)) {
            return null;
        }
        PromoModel promoModel = new PromoModel();
        BeanUtils.copyProperties(promoDo,promoModel);
        promoModel.setPromoItemPrice(BigDecimal.valueOf(promoDo.getPromoItemPrice()));
        // 时间不同 sql.date vs joda-time
        promoModel.setStartTime(new DateTime(promoDo.getStartTime()));
        promoModel.setEndTime(new DateTime(promoDo.getEndTime()));
        return promoModel;
    }

}
